package com.mifan.security;/*
 * @Author Milan
 * @Date 2024/9/15 11:15
 */

import com.mifan.entity.Resources;
import com.mifan.mapper.ResourceMapper;
import com.mifan.service.IResourceService;
import com.mifan.utils.JwtTokenUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private IResourceService resourceService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // TODO 判断是否是登录接口
        StringBuffer requestURL = request.getRequestURL();
        if (requestURL.toString().contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        // TODO 获取token 判断 不能为空 验证
        String token = request.getHeader("Token");
        if (token == null) {
            throw new RuntimeException("Token为空");
        }

        // TODO 验证token
        Boolean validateToken = JwtTokenUtil.validateToken(token);
        if (!validateToken) {
            throw new RuntimeException("Token无效");
        }

        // TODO 解析 token 存入上下文中 验证通过 放行
        String username = JwtTokenUtil.extractUser(token);
        System.out.println("username = " + username);

        // TODO 根据 username 获取权限信息
        List<String> resourcesByUserUsername = resourceService.getResourcesByUserUsername(username);
        List<SimpleGrantedAuthority> resources =
                resourcesByUserUsername
                        .stream()
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());

        // TODO 放入上下文中 权限信息 还没有
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, resources);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        // TODO 处理完成放行
        filterChain.doFilter(request, response);
    }
}
